"""
Copyright (c) 2023 - present SKbioinfo
"""

from flask_restful import Resource, reqparse
from flask import request,jsonify
from flask_login import login_required,current_user
from apps.NGS_API.stock.db_stock import *
from apps.NGS_API.connector.db_common import *
from apps.NGS_API.common.common_time import *
from apps.NGS_API.utils.log_helper import lg
from apps.NGS_API.common.db_table_config import *
import re

class interfaceExtquery(Resource):
    @login_required
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("proj_id",type=str,required=True,help="项目ID输入错误！！")
        parser.add_argument("ext_id",type=str,required=True,help="抽提ID输入错误！！")
        parser.add_argument("sam_id",type=str,required=True,help="样品ID输入错误！！")
        args = parser.parse_args()
        ### SQL: search extracion infos ###
        cols = '''
            volume
        '''
        extraction_query_sql = '''
            SELECT 
                {cols}
            FROM 
                {table_name}
            WHERE {col_name} = \"{id}\"
        '''.format(
            cols = cols,
            col_name = "extraction_id",
            table_name = extraction_qc_db["name"],
            id = args.get("ext_id")
        )
        results = dic_query_info(extraction_query_sql)
        instock_amount = 0
        if len(results) == 0:
            pass
        else:
            instock_amount = results[0]["volume"]
        return {
            "istc_amount":instock_amount,
            "ext_id":args.get("ext_id"),
            "proj_id":args.get("proj_id"),
            "sam_id": args.get("sam_id")
        }
        
class interfaceTableExtractionID(Resource):
    @login_required
    def post(self,id):
        try: 
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                parser = reqparse.RequestParser()
                parser.add_argument("id",type=str,required=True,help="id输入错误！")
                parser.add_argument("proj_id",type=str,required=True,help="项目编号错误！")
                parser.add_argument("ext_id",type=str,required=True,help="抽提编号错误！")
                parser.add_argument("sam_id",type=str,required=True,help="样品编号错误！")
                parser.add_argument("stc_id",type=str,required=True,help="库存编号错误！")
                parser.add_argument("stc_amount",type=str, required=True,help="消耗样品量错误！")
                parser.add_argument("cre_time",type=str,required=True,help="创建时间输入有误！")
                args=parser.parse_args()
                ### transform time format ###
                times = trans_time_format(args.get("cre_time"))
                args["cre_time"] = times
                extraction_cols = '''
                    id,
                    extraction_id,
                    stock_id,
                    sample_id,
                    operate_user,
                    check_user,
                    operate_time,
                    create_time,
                    modify_time
                '''
                extraction_table_values = '''
                    {id},
                    \"{ext_id}\",
                    \"{stc_id}\",
                    \"{sam_id}\",
                    \"{op_user}\",
                    \"{ch_user}\",
                    \"{op_time}\",
                    \"{cre_time}\",
                    \"{md_time}\"
                '''.format(
                    id = id,
                    ext_id = args.get('ext_id'),
                    sam_id = args.get("sam_id"),
                    stc_id = args.get("stc_id"),
                    op_user = current_user.username,
                    ch_user = current_user.username,
                    op_time = get_current_time(),
                    cre_time = times,
                    md_time = get_current_time()
                )
                ### SQL: add extraction infos to database ###
                extraction_add_sql='''
                    INSERT INTO {db_table} (
                        {cols}
                    ) VALUES (
                        {table_values}
                    )
                '''.format(
                    db_table = extraction_db["name"],
                    cols = extraction_cols,
                    table_values = extraction_table_values
                )
                extraction_stock_cols = '''
                    id,
                    stock_id,
                    extraction_id,
                    status,
                    stock_label,
                    stock_locale,
                    instock_type,
                    instock_user,
                    instock_check_user,
                    instock_amount,
                    instock_time,
                    cur_amount,
                    outstock_type,
                    outstock_user,
                    outstock_check_user,
                    outstock_amount,
                    outstock_time,
                    create_time,
                    modify_time
                '''
                stock_table_values = '''
                    {id},
                    \"{stc_id}\",
                    \"{ext_id}\",
                    \"{status}\",
                    \"{stc_label}\",
                    \"{stc_locale}\",
                    \"{istc_type}\",
                    \"{istc_user}\",
                    \"{istc_ch_user}\",
                    \"{istc_amount}\",
                    \"{istc_time}\",
                    \"{cur_amount}\",
                    \"{ostc_type}\",
                    \"{ostc_user}\",
                    \"{ostc_ch_user}\",
                    \"{ostc_amount}\",
                    \"{ostc_time}\",
                    \"{cre_time}\",
                    \"{md_time}\"
                '''.format(
                    id = args.get('id'),
                    stc_id = args.get("stc_id"),
                    ext_id = args.get('ext_id'),
                    status = 1,
                    stc_label = "",
                    stc_locale = "",
                    istc_type = 0,
                    istc_user = "",
                    istc_ch_user = "",
                    istc_amount = 0,
                    istc_time = get_current_time(),
                    cur_amount = 0,
                    ostc_type = 0,
                    ostc_user = "",
                    ostc_ch_user = "",
                    ostc_amount = 0,
                    ostc_time = get_current_time(),
                    cre_time = get_current_time(),
                    md_time = get_current_time()
                )
                ### SQL: add extraction stock infos to database ###
                extraction_stock_sql = '''
                    INSERT INTO {db_table} (
                        {cols}
                    ) VALUES (
                        {table_values}
                    )
                '''.format(
                    db_table = stock_ngs_extraction["name"],
                    cols = extraction_stock_cols,
                    table_values = stock_table_values
                )
                ### SQL: calculate stock amount ###
                sample_cur_amount_sql='''
                    SELECT
                        id, 
                        cur_amount 
                    FROM 
                        {table_name}
                    WHERE 
                        sample_id = \"{sam_id}\"
                '''.format(
                    col = "sample_id",
                    table_name = sample_stock_db["name"],
                    sam_id = args.get("sam_id")
                )
                ### SQL: query sample amount ###
                sample_amount = query_info(sample_cur_amount_sql)
                cur_amount = float(sample_amount[0][1]) - float(args.get("stc_amount"))
                ### SQL: update sample amount ###
                sample_amount_sql = '''
                    UPDATE {table_name} SET 
                        cur_amount={cur_amount}
                    WHERE {col}=\"{sam_id}\"
                '''.format(
                    table_name = sample_stock_db["name"],
                    col="sample_id",
                    sam_id = args.get("sam_id"),
                    cur_amount = cur_amount
                )
                ### PART1: add extraction infos ###
                add_info(extraction_add_sql)
                ### PART2: add extraction stock infos ###
                # add_info(extraction_stock_sql)
                ### PART3: update sample stock amount ###
                update_info(sample_amount_sql)
        except Exception as e:
            lg.error(e)

class interfaceTableExtractionQC(Resource):
    ### CONTRUCTOR ###
    def __init__(self):
        self.sqlscript = create_msyql_sql(data_table=extraction_qc_db)
    
    @login_required
    def get(self):
        infos = {}
        ext_qc_infos = self.sqlscript.create_query_infos()
        infos["ext_qc_infos"] = ext_qc_infos
        response = jsonify(infos)
        response.status_code = 202
        return response
    
    @login_required
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("ext_id",type=str,required=True,help="抽提编号输入有误！")
        parser.add_argument("sam_id",type=str,required=True,help="样品编号输入有误！")
        parser.add_argument("nucleic_type",type=str,required=True,help="核酸类型输入有误！")
        parser.add_argument("proj_id",type=str,required=True,help="项目编号输入有误！")
        parser.add_argument("qc_result",type=str,required=True,help="质控结果输入有误！")
        parser.add_argument("DNA_residue",type=float,required=True,help="DNA残基输入有误！")
        parser.add_argument("concen",type=float,required=True,help="浓度输入有误！")
        parser.add_argument("volume",type=float,required=True,help="体积输入有误！")
        parser.add_argument("op_user",type=str,required=True,help="操作人员输入有误！")
        parser.add_argument("ch_user",type=str,required=True,help="审核人输入有误！")
        parser.add_argument("A260",type=float,required=True,help="A260输入有误！")
        parser.add_argument("A280",type=float,required=True,help="A280输入有误！")
        parser.add_argument("RIN",type=int,required=True,help="RIN值输入有误！")
        parser.add_argument("cre_time",type=str,required=True,help="时间输入有误！")
        parser.add_argument("stock_amount",type=float,required=True,help="投入量输入有误！")
        parser.add_argument("Total_amount",type=float,required=True,help="总量输入有误！")
        args = parser.parse_args()
        times = trans_time_format(args.get("cre_time"))
        args["cre_time"] = times
        extraction_qc_sql = self.sqlscript.create_insert_sql(args)
        add_info(extraction_qc_sql)

def trans_time_format(time):
    if time == 'undefined':
        return get_current_time()
    else:
        tmp_times = time.split('T')
        return tmp_times[0] + " " + tmp_times[1]

class interfaceTablengsLibID(Resource):
    @login_required
    def post(self,id):
        if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
            pass
        else:
            parser = reqparse.RequestParser()
            parser.add_argument("id",type=str,required=True,help="id输入错误！")
            parser.add_argument("lib_id",type=str,required=True,help="文库编号输入错误！")
            parser.add_argument("sam_id",type=str,required=True,help="样品编号输入错误！")
            parser.add_argument("ext_id",type=str,required=True,help="抽提编号输入错误！")
            parser.add_argument("stc_amount",type=str,required=True,help="消耗库存量输入有误！")
            parser.add_argument("cre_time",type=str,required=True,help="文库创建时间输入有误！")
            args=parser.parse_args()
            ### SQL:create time ###
            times = trans_time_format(args.get("cre_time"))
            args["cre_time"] = times
            ### SQL: query extraction stock ID ###
            extraction_stockID_sql='''
                SELECT 
                    stock_id
                FROM {table_name}
                WHERE {sam_col} = \"{sam_id}\" AND {ext_col} = \"{ext_id}\"
            '''.format(
                    table_name=extraction_db["name"],
                    sam_col="sample_id",
                    sam_id=args.get("sam_id"),
                    ext_col="extraction_id",
                    ext_id=args.get("ext_id")
            )
            ### STOCK ID FROM extraction sheet ###
            stc_id = query_info(extraction_stockID_sql)[0][0]
            ### SQL: add library infos to database ###
            library_cols = '''
                id,
                library_id,
                stock_id,
                sample_id,
                operate_user,
                check_user,
                operate_time,
                create_time,
                modify_time
            '''
            library_table_values = '''
                {id},
                \"{lib_id}\",
                \"{stc_id}\",
                \"{sam_id}\",
                \"{op_user}\",
                \"{ch_user}\",
                \"{op_time}\",
                \"{cre_time}\",
                \"{md_time}\"
            '''.format(
                id = args.get('id'),
                lib_id = args.get('lib_id'),
                sam_id = args.get('sam_id'),
                stc_id = stc_id,
                op_user = current_user.username,
                ch_user = current_user.username,
                op_time = get_current_time(),
                cre_time = args.get('cre_time'),
                md_time = get_current_time()
            )
            ### SQL: add library infos to database ###
            library_add_sql = '''
                INSERT INTO {db_table} (
                    {cols}
                ) VALUES (
                    {table_values}
                )
            '''.format(
                db_table = ngsLib_db["name"],
                cols = library_cols,
                table_values =  library_table_values
            )
            ### PART1: add library infos to database ### 
            add_info(library_add_sql)
            ### PART2: ###
            ### PART3: ###

class interfaceTablengsLibQC(Resource):
    ### CONTRUCTOR ###
    def __init__(self):
        self.sqlscript = create_msyql_sql(data_table=ngsLib_qc_db)
    
    @login_required
    def get(self):
        infos = {}
        Lib_qc_infos = self.sqlscript.create_query_infos()
        infos["Lib_qc_infos"] = Lib_qc_infos
        response = jsonify(infos)
        response.status_code = 202
        return response
    
    @login_required
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("ext_id",type=str,required=True,help="抽提编号输入有误！")
        parser.add_argument("stock_amount",type=float,required=True,help="抽提入库量输入错误！")
        parser.add_argument("ext_amount",type=float,required=True,help="抽提量输入有误！")
        parser.add_argument("sam_id",type=str,required=True,help="样品编号输入有误！")
        parser.add_argument("lib_id",type=str,required=True,help="文库编号输入有误！")
        parser.add_argument("PCR_circles",type=int,required=True,help="PCR循环数！")
        parser.add_argument("Index_ID",type=str,required=True,help="barcodeID输入有误")
        parser.add_argument("concen",type=float,required=True,help="浓度输入有误！")
        parser.add_argument("volume",type=float,required=True,help="体积输入有误！")
        parser.add_argument("op_user",type=str,required=True,help="操作人员输入有误！")
        parser.add_argument("ch_user",type=str,required=True,help="审核人输入有误！")
        parser.add_argument("cre_time",type=str,required=True,help="创建时间输入有误！")
        parser.add_argument("Total_amount",type=float,required=True,help="总量输入有误！")
        parser.add_argument("fragment_size",type=int,required=True,help="片段大小输入有误！")
        parser.add_argument("qc_result",type=str,required=True,help="质控结果输入有误！")
        args = parser.parse_args()
        ### SQL: add qc infos ###
        times = trans_time_format(args.get("cre_time"))
        args["cre_time"] = times
        library_qc_sql = self.sqlscript.create_insert_sql(args)
        ### record remain amount ###   
        remain_amount = args.get("ext_amount") - args.get("stock_amount")
        ### SQL: update extraction amount ###
        ext_amount_sql = '''
            UPDATE 
                {table_name} 
            SET 
                volume = {remain_amount}
            WHERE {col_name} = \"{ext_id}\"
        '''.format(
            table_name = extraction_qc_db["name"],
            col_name = "extraction_id",
            remain_amount = remain_amount,
            ext_id = args.get("ext_id")
        )
        ### STEP 1: add qc infos ###
        add_info(library_qc_sql)
        ### STEP 2: update extraction amount ###
        update_info(ext_amount_sql)
    @login_required
    def put(self):
        pass
       
class interfacegenerateExtID(Resource):
    @login_required
    def post(self):
        try:
            ### SQL: query extraction ID ###
            extraction_id_sql = '''
                SELECT 
                    id,
                    extraction_id
                FROM {table_name}
            '''.format(
                table_name = extraction_db["name"]
            )
            extraction_infos = query_info(extraction_id_sql)
            ### Extraction ID ###
            if not extraction_infos:
                return {"id":0,"ext_id":"992023033099000"}
            else:
                ids = [ extraction[0] for extraction in extraction_infos]
                max_id = Max(ids)
                ext_ids = [ int(re.sub("[A-Za-z]","",extraction[1])) for extraction in extraction_infos ]
                max_ext_id = Max(ext_ids)
                return {"id":max_id,"ext_id":max_ext_id}
        except Exception as e:
            lg.error(e)

class interfacegenerateLibID(Resource):
    @login_required
    def post(self):
        try:
            ### SQL: query extraction ID ###
            ngsLib_id_sql = '''
                SELECT 
                    id,
                    library_id
                FROM {table_name}
            '''.format(
                table_name = ngsLib_db["name"]
            )
            Lib_infos = query_info(ngsLib_id_sql)
            ### Extraction ID ###
            if not Lib_infos:
                return {"id":0,"lib_id":"992023033099000"}
            else:
                ids = [ lib[0] for lib in Lib_infos]
                max_id = Max(ids)
                Lib_ids = [ int(re.sub("[A-Za-z]","",Lib[1])) for Lib in Lib_infos ]
                max_ext_id = Max(Lib_ids)
                return {"id":max_id,"lib_id":max_ext_id}
        except Exception as e:
            lg.error(e)
            
class interfacegenerateStcID(Resource):
    @login_required
    def post(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument("table_name",type=str,required=True,help="输入表格问题")
            args=parser.parse_args()
            ### SQL: query extraction ID ###
            Stc_id_sql = '''
                SELECT 
                    id,
                    stock_id
                FROM {table_name}
            '''.format(
                table_name = args.get("table_name")
            )
            Stc_infos = query_info(Stc_id_sql)
            ### Extraction ID ###
            if not Stc_infos:
                return {"id":0,"stc_id":"992023033099000"}
            else:
                ids = [ lib[0] for lib in Stc_infos ]
                max_id = Max(ids)
                stc_ids = [ int(re.sub("[A-Za-z]","",stc[1])) for stc in Stc_infos ]
                max_ext_id = Max(stc_ids)
                return {"id":max_id,"stc_id":max_ext_id}
        except Exception as e:
            lg.error(e)

def Max(numbers):
    max = 0
    for num in numbers:
        if num > max:
            max = num
        else:
            pass
    return max
    
class interfaceTableupload(Resource):
    @login_required
    def get(self):
        # try:
            infos={}
            ### SQL: query sample infos ###
            query_sample_sql = '''
                SELECT
                    tb1.id,
                    tb1.sample_id,
                    tb1.project_id,
                    tb3.instock_amount,
                    tb3.cur_amount,
                    tb2.status,
                    tb3.status,
                    tb1.unit,
                    tb1.primary_sample_id,
                    tb1.primary_project_id
                FROM {table_one} as tb1
                LEFT JOIN {table_three} as tb3
                ON tb1.sample_id = tb3.sample_id 
                INNER JOIN {table_two} as tb2
                ON tb1.project_id = tb2.project_id
                AND tb2.status=0
            '''.format(
                table_one = sample_db["name"],
                table_two = project_db["name"],
                table_three = sample_stock_db["name"], 
            )
            ### collect sample infos ###
            sample_infos = query_info(query_sample_sql)
            query_extraction_sql = '''
                SELECT
                    id,
                    extraction_id,
                    sample_id,
                    stock_id
                FROM {table_one}
            '''.format(
                table_one = extraction_db["name"],
            )
            ### collect extraction infos ###
            extraction_infos=query_info(query_extraction_sql)
            ### SQL: query ngsLib infos ###
            query_ngsLib_sql = '''
                SELECT
                    id,
                    library_id,
                    sample_id,
                    stock_id
                FROM {table_name}
            '''.format(
                table_name = ngsLib_db["name"]
            )
            ### collect ngsLib infos ###
            ngsLib_infos = query_info(query_ngsLib_sql)
            ### collect basic infos ###
            table_infos = [] 
            if not sample_infos:
                if not extraction_infos: 
                    if not ngsLib_infos:
                        pass
                    if ngsLib_infos:
                        pass
                if extraction_infos:
                    if not ngsLib_infos:
                        pass
                    if ngsLib_infos:
                        pass
            elif sample_infos:
                ### merge infos samples&extractions ###
                samples = {}
                for sample in sample_infos:
                    samples[sample[1]] = {
                        "id": sample[0],
                        "sample_id": sample[1],
                        "project_id": sample[2],
                        "init_amount": sample[3],
                        "cur_amount": sample[4],
                        "status": sample[5],
                        "stc_status": sample[6],
                        "unit": sample[7].split(",")[1]
                    }
                if extraction_infos:
                    extractions = {}
                    for extraction in extraction_infos:
                        extractions[extraction[1]] = {
                            "id":extraction[0],
                            "extraction_id":extraction[1],
                            "sample_id":extraction[2],
                            "stock_id":extraction[3] 
                        }
                    if not ngsLib_infos:
                        ## merge samples&extraction ##
                        ext_samples = [ content["sample_id"] for _,content in extractions.items()]
                        for sam_id,sam_con in samples.items():
                            if sam_id in ext_samples:
                                for ext_id,ext_con in extractions.items():
                                    if sam_id == ext_con["sample_id"]:
                                        table_infos.append({
                                            "proj_id": samples[ext_con["sample_id"]]["project_id"],
                                            "sam_id": sam_id,
                                            "ext_id": ext_id,
                                            "lib_id": "NA",
                                            "init_amount": samples[ext_con["sample_id"]]["init_amount"],
                                            "cur_amount": samples[ext_con["sample_id"]]["cur_amount"],
                                            "stc_status": samples[ext_con["sample_id"]]["stc_status"],
                                            "unit": samples[ext_con["sample_id"]]["unit"],
                                            "flag":False
                                        })
                            else:
                                table_infos.append({
                                    "proj_id": samples[sam_con["sample_id"]]["project_id"],
                                    "sam_id": sam_id,
                                    "ext_id": "NA",
                                    "lib_id": "NA",
                                    "init_amount": samples[sam_con["sample_id"]]["init_amount"],
                                    "cur_amount": samples[sam_con["sample_id"]]["cur_amount"],
                                    "stc_status": samples[sam_con["sample_id"]]["stc_status"],
                                    "unit": samples[sam_con["sample_id"]]["unit"],
                                    "flag":False
                                })
                    ### extractions&samples&ngsLib ###
                    elif ngsLib_infos:
                        ngsLib = {}
                        for lib in ngsLib_infos:
                            ngsLib[lib[1]] = {
                                "id": lib[0],
                                "lib_id": lib[1],
                                "sample_id": lib[2],
                                "stock_id": lib[3]
                            }
                        ### collect samples&extraction infos ###
                        table_infos = []
                        ### temp infos ###
                        tmp_infos = {}
                        ext_samples = { content["sample_id"]:ext_id for ext_id,content in extractions.items()}
                        for sam_id,sam_con in samples.items():
                            if sam_id in ext_samples.keys():
                                for _,ext_con in extractions.items():
                                    tmp_infos[ext_con["stock_id"]] = {
                                        "id": ext_con["id"],
                                        "sample_id": ext_con["sample_id"],
                                        "stock_id": ext_con["stock_id"],
                                        "extraction_id": ext_con["extraction_id"],
                                        "project_id": samples[ext_con["sample_id"]]["project_id"],
                                        "init_amount": samples[ext_con["sample_id"]]["init_amount"],
                                        "cur_amount": samples[ext_con["sample_id"]]["cur_amount"],
                                        "stc_status": samples[ext_con["sample_id"]]["stc_status"],
                                        "unit": samples[ext_con["sample_id"]]["unit"],
                                        "status": samples[ext_con["sample_id"]]["status"]
                                    }
                            else:
                                table_infos.append({
                                    "proj_id": samples[sam_con["sample_id"]]["project_id"],
                                    "sam_id": sam_id,
                                    "ext_id": "NA",
                                    "lib_id": "NA",
                                    "init_amount": samples[sam_con["sample_id"]]["init_amount"],
                                    "cur_amount": samples[sam_con["sample_id"]]["cur_amount"],
                                    "unit":samples[ext_con["sample_id"]]["unit"],
                                    "stc_status": "NA",
                                    "stc_status": samples[sam_id]["stc_status"],
                                    "flag":False
                                })
                        ### SQL: library stock ###
                        lib_stocks = [ lib_infos["stock_id"] for _,lib_infos in ngsLib.items() ]
                        if len(tmp_infos) == 0:
                            pass
                        else:    
                            for ext_id,ext_infos in extractions.items():
                                stock_id = ext_infos["stock_id"]
                                if stock_id in lib_stocks:
                                    for lib_id,lib_infos in ngsLib.items():
                                        if lib_infos["stock_id"] == stock_id:
                                            table_infos.append(
                                                {
                                                    "lib_id": lib_id,
                                                    "proj_id": tmp_infos[stock_id]["project_id"],
                                                    "sam_id": tmp_infos[stock_id]["sample_id"],
                                                    "ext_id": tmp_infos[stock_id]["extraction_id"],
                                                    "init_amount": tmp_infos[stock_id]["init_amount"],
                                                    "cur_amount": tmp_infos[stock_id]["cur_amount"],
                                                    "stc_status": tmp_infos[stock_id]["stc_status"],
                                                    "unit": tmp_infos[stock_id]["unit"],
                                                    "flag":False
                                                }
                                            )
                                else:
                                    table_infos.append(
                                        {
                                            "lib_id": "NA",
                                            "proj_id": samples[ext_infos["sample_id"]]["project_id"],
                                            "sam_id": ext_infos["sample_id"],
                                            "ext_id": ext_infos["extraction_id"],
                                            "init_amount": samples[ext_infos["sample_id"]]["init_amount"],
                                            "cur_amount": samples[ext_infos["sample_id"]]["cur_amount"],
                                            "stc_status": samples[ext_infos["sample_id"]]["stc_status"],
                                            "unit": samples[ext_infos["sample_id"]]["unit"],
                                            "flag":False
                                        }
                                    )
                elif not extraction_infos:
                    if ngsLib_infos:
                        for sam_id,content in samples.items():
                            table_infos.append(
                                {   
                                    "proj_id": content["project_id"],
                                    "sam_id": sam_id,
                                    "ext_id": "NA",
                                    "lib_id": "NA",
                                    "init_amount": content["init_amount"],
                                    "cur_amount": content["cur_amount"],
                                    "stc_status": content["stc_status"],
                                    "unit":content["unit"],
                                    "flag":False
                                }
                            )
                    elif not ngsLib_infos:
                        for sam_id,content in samples.items():
                            table_infos.append(
                                {   
                                    "id": content["id"],
                                    "proj_id": content["project_id"],
                                    "sam_id": sam_id,
                                    "ext_id": "NA",
                                    "lib_id": "NA",
                                    "init_amount": content["init_amount"],
                                    "cur_amount": content["cur_amount"],
                                    "stc_status": content["stc_status"],
                                    "unit":content["unit"],
                                    "flag":False
                                }
                            )
            ### collect table infos ###
            if not table_infos:
                table_infos=[
                    {
                        "id":"NA",
                        "proj_id": "NA",
                        "sam_id": "NA", 
                        "ext_id": "NA",
                        "lib_id": "NA",
                        "init_amount": "NA",
                        "cur_amount": "NA",
                        "stc_amount":"NA",
                        "unit":"NA",
                        "flag": False
                    }
                ]
            else:
                table_infos = table_infos
            ### collect final infos ###
            infos["table_infos"] = table_infos    
            response=jsonify(infos)
            response.status_code = 202
            return response
        # except Exception as e:
        #     lg.error(e)